import refreshConfig from 'refresh-config'
import { DOCUMENT_STATE, DOCUMENT_VISIBILITY_CHANGE, DOCUMENT_HIDDEN } from 'utils/document-visiable'

// import diversion from 'utils/diversion'
export var globalMixins = {
  mounted () {
    if (this.needInterval()) {
      this.addRereshInterval()
      this.addDocumentStateListener()
    }
  },
  destroyed () {
    this.clearRreshInterval()
  },
  methods: {
    needInterval () {
      if (typeof this.requestRestfulData === 'function') {
        let name = this.$route.name
        let path = this.$route.path
        if (path.indexOf('dashboard') !== -1) {
          if (!refreshConfig['dashboard'] || !refreshConfig['dashboard'].isRefresh) {
            return false
          }
        }
        if (!name || !refreshConfig[name] || !refreshConfig[name].isRefresh) {
          return false
        }
        return true
      }
      return false
    },
    addRereshInterval () {
      let path = this.$route.path.split('/')
      // 去除第一个空值和id值
      path.shift()
      path.shift()
      this._requestRestfulDataIntervalId = []
      path.forEach(item => {
        this._requestRestfulDataIntervalId.push(setInterval(() => {
          !document[DOCUMENT_HIDDEN] && this.requestRestfulData()
        }, refreshConfig[item].refreshFrequency))
      })
    },
    // 添加窗口隐藏的监听
    addDocumentStateListener () {
      document.addEventListener(DOCUMENT_VISIBILITY_CHANGE, (e) => {
        // 开始或停止状态处理
        if (document[DOCUMENT_STATE] === 'hidden') {
          this._intervalShouldRestore = true
          this.clearRreshInterval()
        } else if (document[DOCUMENT_STATE] === 'visible' && this._intervalShouldRestore) {
          this._intervalShouldRestore = false
          this.addRereshInterval()
        }
      }, false)
    },
    clearRreshInterval () {
      if (this._requestRestfulDataIntervalId) {
        this._requestRestfulDataIntervalId.forEach(item => {
          window.clearInterval(item)
        })
        this._requestRestfulDataIntervalId = []
      }
    },
    handleError (err) {
      if (err.response) {
        let errData = err.response.data
        let errCode = errData.error.code
        switch (errCode) {
          case 4031003:
          case 4031022:
            if (this.$route.fullPath === '/dashboard/independentPm') {
              return
            } else {
              this.$router.push('/login')
            }
            break
          default:
            console.log('请求出错')
        }
      } else {
        console.log('Error', err.message)
      }
    }
  }
}
